import socket
import time

HOST = '0.0.0.0'
PORT = 12345

def udp_server():
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        s.bind((HOST, PORT))
        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] UDP服务器已启动，监听 {PORT} 端口...")
        
        client_timeout = 30  # 客户端超时时间(秒)
        clients = {}  # 记录客户端最后活动时间
        
        while True:
            try:
                data, addr = s.recvfrom(1024)
                current_time = time.time()
                
                # 记录或更新客户端活动时间
                if addr not in clients:
                    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 新客户端连接: {addr}")
                clients[addr] = current_time
                
                print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 收到来自 {addr} 的数据: {data.decode()}")
                s.sendto(b'UDP Server received: ' + data, addr)
                
                # 检查超时的客户端
                for client_addr, last_active in list(clients.items()):
                    if current_time - last_active > client_timeout:
                        print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 客户端 {client_addr} 超时断开")
                        del clients[client_addr]
                        
            except KeyboardInterrupt:
                print(f"\n[{time.strftime('%Y-%m-%d %H:%M:%S')}] 服务器关闭")
                break
            except Exception as e:
                print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 发生错误: {str(e)}")
                continue

if __name__ == '__main__':
    udp_server()